<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="10"
          ><el-input
            clearable
            placeholder="请输入内容"
            v-model="queryshuju.query"
            @clear="qingchu"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="shuju"
            ></el-button>
          </el-input>
          <div class="grid-content bg-purple"></div
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="duihuakuang = true"
            >添加用户</el-button
          >
          <div class="grid-content bg-purple"></div
        ></el-col>
      </el-row>
      <el-table stripe border :data="uesrlist">
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="mobile"> </el-table-column>
        <el-table-column label="角色" prop="role_name"> </el-table-column>
        <el-table-column label="状态">
          <!--  <template slot-scope="scope">
             {{scope.row}} -->
          <template v-slot:default="scope">
            <!--  {{ scope.row }} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
          <!--  <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
            </el-switch>
          </template> -->
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template v-slot:default="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->

            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                @click="quanxianfenpei(scope.row)"
                icon="el-icon-setting"
                size="mini"
                ><!--  @click="setRole(scope.row)" --></el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryshuju.pagenum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="queryshuju.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      @close="guanbi"
      title="添加用户"
      :visible.sync="duihuakuang"
      width="50%"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addfrom"
        :rules="addfromrules"
        ref="addfromref"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addfrom.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addfrom.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addfrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addfrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="duihuakuang = false">取 消</el-button>
        <el-button type="primary" @click="queding">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户"
      :visible.sync="duihuakuang2"
      @close="editDialogClosed"
      width="50%"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="usfrom"
        :rules="usfromrules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="usfrom.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="usfrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="usfrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="duihuakuang2 = false">取 消</el-button>
        <el-button type="primary" @click="queding2">确 定</el-button>
      </span>
    </el-dialog>
    <!--  @close="quanxian" -->
    <el-dialog
      title="分配权限"
      @close="quanxian"
      :visible.sync="quanxiankuang"
      width="50%"
    >
      <div>
        <p>当前用户：{{ userInfo.username }}</p>
        <p>当前角色：{{ userInfo.role_name }}</p>
        <p>
          分配角色：
          <el-select v-model="selectid" placeholder="请选择">
            <el-option
              v-for="item in fenpeilist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="quanxiankuang = false">取 消</el-button>
        <el-button type="primary" @click="quanxiankuangclick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "users",
  data() {
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }

      cb(new Error("请输入合法的邮箱"));
    };
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };

    return {
      //添加用户对话框的显示与隐藏
      duihuakuang: false,
      duihuakuang2: false,
      queryshuju: {
        query: "", //搜索内容
        pagenum: 1, //当前页码
        pagesize: 2, //每页显示条数
      },
      uesrlist: [], //数据列表
      total: 0, //一共几条数据
      usfrom: [],
      //添加用户的表单数据
      addfrom: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      quanxiankuang: false,
      usfrom: {
        username: "",
        email: "",
        mobile: "",
      },
      fenpeilist: [],
      selectid: "",
      userInfo: {},
      usfromrules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //添加表单的验证规则
      addfromrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    queding2() {
      this.$refs.editFormRef.validate(async (valid) => {
        console.log(this.usfrom);
        if (!valid) return;
        const { data: res } = await this.$http.put("users/" + this.usfrom.id, {
          email: this.usfrom.email,
          mobile: this.usfrom.mobile,
        });
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.duihuakuang2 = false;
        this.shuju();
      });
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    removeUserById(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.removeUserByIds(id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async removeUserByIds(id) {
      const { data: res } = await this.$http.delete(`users/${id}`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.shuju();
    },
    async showEditDialog(id) {
      console.log(`user/:${id}`);
      const { data: res } = await this.$http.get(`users/${id}`);
      /*  console.log(res); */
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.usfrom = res.data;
      console.log(this.usfrom);
      this.duihuakuang2 = true;
    },
    queding() {
      /*  console.log(this.$refs.addfromref.validate); */
      this.$refs.addfromref.validate(async (valid) => {
        if (!valid) return;
        //发起请求添加
        const { data: res } = await this.$http.post("users", this.addfrom);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.duihuakuang = false;
        this.shuju();
      });
    },
    guanbi() {
      this.$refs.addfromref.resetFields();
    },
    qingchu() {
      this.queryshuju.query = "";
      this.shuju();
    },
    //监听状态控制开关
    async userStateChanged(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      console.log(res.meta.status);
      if (res.meta.status != 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error(res.meta.msg);
      } else this.$message.success(res.meta.msg);
    },
    //翻页和跳转页面带上最新的参数重新请求
    handleSizeChange(newsize) {
      this.queryshuju.pagesize = newsize;
      this.shuju();
    },
    handleCurrentChange(newpage) {
      this.queryshuju.pagenum = newpage;
      this.shuju();
    },
    async shuju() {
      //带上自己的数据从服务器拿最新处理后的
      /* get请求需要携带params */
      const { data: shujubao } = await this.$http.get("users", {
        params: this.queryshuju,
      });
      /*  console.log(shujubao); */
      if (shujubao.meta.status != 200)
        return this.$message.error("获取管理员列表失败");
      this.uesrlist = shujubao.data.users;
      this.total = shujubao.data.total;
      /*  console.log(this.uesrlist);
      console.log(this.total); */
    },
    async quanxianfenpei(userInfo) {
      this.userInfo = userInfo;

      const { data: res } = await this.$http.get("roles");

      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.fenpeilist = res.data;
      this.quanxiankuang = true;
    },
    async quanxiankuangclick() {
      if (!this.selectid) {
        return this.$message.error("请选择要分配的角色");
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectid,
        }
      );
      if (res.meta.status != 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.shuju();
      this.quanxiankuang = false;
    },
    quanxian() {
      this.selectid = "";
      this.userInfo = {};
    },
  },
  created() {
    this.shuju();
  },
};
</script>

<style lang="less" scoped>
</style>